package com.laicunba.ext.web.controller.h5.activity;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.constant.GloabConstant;
import com.laicunba.ext.service.SlaveActivityJoinService;
import com.laicunba.ext.service.SlaveUserService;
import com.laicunba.ext.web.controller.SuiCunBaoBaseController;
import com.laicunba.pojo.UserDO;
import com.laicunba.pojo.vo.WeiXinVO;
import com.laicunba.service.ActivityService;
import com.laicunba.service.PicService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.UserService;
import com.laicunba.service.WeiXinService;
import com.laicunba.util.QRcodeUtil;
import com.laicunba.util.StringUtil;
 
//@Controller
@RequestMapping(value = "/h5/ext/activity")
public class GainGoldController extends SuiCunBaoBaseController {
	private static final Logger LOG = Logger.getLogger(GainGoldController.class);
	@Autowired
	private RegistryService registryService;
	@Autowired
	private WeiXinService weiXinService;
	@Autowired
	private UserService userService;
	@Autowired
	private PicService picService;
	@Value("${ftp.dir:/resource/}")
	private String ftpDir;
	@Autowired
	private SlaveUserService slaveUserService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private SlaveActivityJoinService slaveActivityJoinService;
	
	@RequestMapping(value = "/gain_gold.htm")
	public ModelAndView gainGold(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("gain_gold.jsp");
		try {
			//查询剩余黄金
			Map<String, Object> activityJoinData = slaveActivityJoinService.findTotalReward("20170410", null);
			BigDecimal totalReward = new BigDecimal(0);
			if(activityJoinData != null && activityJoinData.size() > 0) {
				totalReward = (BigDecimal) activityJoinData.get("total_reward");
				if(totalReward == null) {
					totalReward = new BigDecimal(0);
				}
			}
			view.addObject("remainGold", new BigDecimal(1000).subtract(totalReward));

			UserDO userDO = getCurrentUser(request);
			String uri = request.getRequestURI();
			uri = uri.substring(request.getContextPath().length());
			String link = GloabConstant.WEB_PATH + uri;
			if(StringUtil.isNotEmpty(request.getQueryString())) {
				link += "?" + request.getQueryString();
			}
			if (userDO == null) {
//				view = new ModelAndView("redirect:/h5/login.htm?tab=account&returnUrl="+link);
				return view;
			}
			if (StringUtil.isEmpty(userDO.getInviteCode())) {
				// 生成邀请码
				userDO.setInviteCode(getRandomString());
			}
			if (StringUtil.isEmpty(userDO.getInviteQrCode()) && StringUtil.isNotEmpty(userDO.getInviteCode())) {
				File qrcodeDir = new File(GloabConstant.PIC_ROOT + "/invite/");
				if (!qrcodeDir.exists()) {
					qrcodeDir.mkdirs();
				}
				File qrCodeFile = new File(qrcodeDir, userDO.getId() + ".png");
				try {
					QRcodeUtil.make(GloabConstant.WEB_PATH + "/h5/regist_new.jsp?invite_code=" + userDO.getInviteCode()
						+"&mobile="+userDO.getMobile().toString().substring(0,3)+"****"+userDO.getMobile().toString().substring(7), qrCodeFile, 300, 300);
					userDO.setInviteQrCode("invite/" + userDO.getId() + ".png");
					picService.upload2Ftp(new FileInputStream(qrCodeFile), ftpDir+"invite/" + userDO.getId() + ".png");
					userService.updateSkipCheckOwner(userDO);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			WeiXinVO weiXinVO = new WeiXinVO();
			weiXinVO.setLink(link);
			LOG.info(String.format("【20170410邀请好友活动】url=[%s]", "u."+weiXinVO.getLink()));
			weiXinVO = weiXinService.getWeiXinVO(weiXinVO);
			LOG.info(String.format("【20170410邀请好友活动】url=[%s]", "u."+weiXinVO.getLink()));
			view.addObject("weiXinVO",weiXinVO);
			view.addObject("inviteCode", userDO.getInviteCode());
			view.addObject("mobile",userDO.getMobile().toString().substring(0,3)+"****"+userDO.getMobile().toString().substring(7));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return view;
	}

	private String getRandomString() {
		String base = "0123456789";
		// 生成字符串从此序列中取
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		String inviteCode = sb.toString();
		List<UserDO> userDOList = userService.findListByInviteCode(inviteCode);
		if (userDOList != null && userDOList.size() > 0) {
			inviteCode = getRandomString();
		}
		return inviteCode;
	}
}
